﻿using WoodAdmin.Common.Extention;
using WoodAdmin.Common.Helper;
using WoodAdmin.Models;
using WoodAdmin.Repository;
using SqlSugar;
using System.Collections.Generic;
using System.Linq;
using SqlSugar.Extensions;

namespace WoodAdmin.Services
{
    public class AccessService : BaseService<SysAccess>
	{
        /// <summary>
        /// 当前用户的所有权限节点
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
		public List<SysNode> CurrentUserAuthNode(int userid)
        {
            List<int> roleIds = Db.Queryable<SysUserRole>().Where(r => r.UserID == userid).Select(r => r.RoleID).ToList();
            var nodes = Db.Queryable<SysNode, SysAccess, SysGroup>((n, acc, g) => new object[] {
                JoinType.Inner,n.ID == acc.NodeID,
                JoinType.Inner,g.ID == n.GroupID
            }).Where((n, acc, g) => roleIds.Contains(acc.RoleID))
            .Select((n, acc, g) => new SysNode { 
                ID = n.ID, 
                Title = n.Title, 
                IcoCss = n.IcoCss, 
                Link = n.Link,
                GroupID = n.GroupID,
                NodeLevel = n.NodeLevel, 
                DisplayFlag = n.DisplayFlag, 
                Pid = n.Pid,
                Name = n.Name
            }).PartitionBy(n=>new{n.ID,n.Title,n.IcoCss,n.Link,n.GroupID,n.NodeLevel,n.DisplayFlag,n.Pid,n.Name}).Take(1).ToList()
            .ToList();
            return nodes;
        }

        /// <summary>
        /// 判断用户是否具有某个操作的权限
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public bool ActionPermission(string controller,string action)
        {
            List<SysNode> userPermission = GlobalHelper.CurrentAuthNode();
            var ctrPermission = userPermission.FirstOrDefault(a => a.Name.ToLower().Equals(controller.ToLower()));
            if (ctrPermission!=null)
            {
                var actPermission = userPermission.FirstOrDefault(a => a.Name.ToLower().Equals(action.ToLower()) && a.Pid.ObjToInt() == ctrPermission.ID);
                if (actPermission!=null)
                {
                    return true;
                }
            }
            return false;
        }
	}
}